package cn.com.infcn.monitor.server;


import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.infcn.monitor.task.IoTask;

/**
 * 
 * @author jjs
 *
 */
public class ServerHandler extends IoFilterAdapter implements IoHandler {
	private final static Logger logger = LoggerFactory.getLogger(MonitorServer.class);
	
    private static ServerHandler samplMinaServerHandler = null;  
  
    public static ServerHandler getInstances() {  
        if (null == samplMinaServerHandler) {
        	synchronized (ServerHandler.class) {
        		if (null == samplMinaServerHandler) {
        			samplMinaServerHandler = new ServerHandler();
        		}
			}
        }  
        return samplMinaServerHandler;  
    }  
  
    private ServerHandler() {  
  
    }  
  
    // 当连接后打开时触发此方法，一般此方法与 sessionCreated 会被同时触发  
    public void sessionOpened(IoSession session) throws Exception {  
    }  
    public void sessionClosed(IoSession session) {  
    }  
    public void messageReceived(IoSession session, Object message)  
            throws Exception {    
//    	System.out.println(message);
//        if (message instanceof UserInfo) {  
//            UserInfo text = (UserInfo) message;  
//            System.out.println("服务器接收到从客户端的姓名："+text.getName());  
//            System.out.println("服务器接收到从客户端的QQ："+text.getQQNum());  
//        }else if (message instanceof List){
//        	List list = (List) message;
//        	System.out.println("else if:"+list.get(0));
//        }else{
//        	System.out.println("else:"+message);
//        }
    	
    	IoTaskFactory factory = IoTaskFactory.getInstance();
		IoTask task = factory.createtTask(session, message);

		if (task == null)
			return;

		try {
			task.execute();
		} catch (Exception e) {
			logger.error("task execute error: {}", e);
//			session.write();
		}
    }  
  
    public void exceptionCaught(IoSession arg0, Throwable arg1)  
            throws Exception {  
    	arg1.printStackTrace();
    	System.out.println("error--");
    }  
  
    // 当消息传送到客户端后触发  
    public void messageSent(IoSession arg0, Object arg1) throws Exception {  
          System.out.println("send--");
    }  
  
    // 当一个新客户端连接后触发此方法.  
    public void sessionCreated(IoSession arg0) throws Exception {  
          System.out.println("create--");
    }  
  
    // 当连接空闲时触发此方法.  
    public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {  
          
    }
  
}  